package com.sz.zhiling.myinteceptor;

import com.sz.zhiling.common.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtils jwtUtils;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler){
        String auth = request.getHeader("Auth");//从请求作用域中得到
        if(auth == null){
            try {
                Claims claims = jwtUtils.parseToken(auth);//解析token
                Object obj = claims.get("roles");
                String roles = (String) obj;
                if(roles != null && roles.equals("delete")){
                    request.setAttribute("roles","delete");
                    return true;//放行
                }else{
                    return false;//拦截
                }
            } catch (Exception e) {
                System.out.println("解析token异常");
                return false;
            }
        }
        return false;
    }
}
